import axios from 'axios'
import { Message, Loading } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'

let loading

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 60000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent

    if (store.getters.token) {

      config.headers['access-token'] = getToken()
    }
    console.log(Loading)
    loading = Loading.service({
      lock: true,
      text: 'Loading',
      spinner: 'el-icon-loading',
      background: 'rgba(0, 0, 0, 0.7)'
    })
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {
    loading.close()
    // const res = response.data
    return response.data
  },
  error => {
    loading.close()
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

/**
*** @title：工程请求方式
*** @param：
*** @author：lupan
*** @desc：
*** @date：2019-11-12 14:31:44
**/
const fetch = (url, params = {}, config) => {
  return new Promise((reslove, reject) => {
    service.post(url, params).then(res => {
      reslove(res)
    }).catch(err => {
      console.log('err' + err) // for debug
      Message({
        message: err.message,
        type: 'error',
        duration: 5 * 1000
      })
      return Promise.reject(err)
    })
  })
}

export default fetch
